//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommunityServer.Components;

namespace CommunityServer.Controls
{
	/// <summary>
	/// Populates a theme defining the title bar of a page, including the logo area, search, and tab strip
	/// </summary>
	public class TitleBar : TemplatedWebControl
	{
		#region Private Data Storage
		
		private CSContext _csContext = CSContext.Current;
		
		private TextBox _titleBarSearchText;
		private IButton _titleBarSearchButton;
		private DropDownList _titleBarSearchDropDownList;
		private EditableLink _titleBarSiteName;
		private HyperLink _titleBarDomainName;
		private InlineTextEdit _titleBarSiteDescription;
		private Control _titleBarSearchInArea;
		//private TabStrip _titleBarTabStrip;

		#endregion

		#region Contructor

		public TitleBar() : base() 
		{
		}

		#endregion

		#region Properties

		/// <summary>
		/// Gets or sets the selected item.  Is automatically populated by the SelectedNavigation control
		/// </summary>
		[
		    Bindable(true),
		        Category("Behavior"),
		        Description("Gets or sets the selected item."),
		        DefaultValue(""),
		]
		public string SelectedItem
		{
			get
			{
			    Object state = ViewState["SelectedItem"];
				if(state == null)
					state = Context.Items["SelectedNavigation"];

				if(state == null)
					state = this._csContext.ApplicationType.ToString().ToLower() ; 
					
				return state == null ? "" : (string) state;
			}
			set
			{
				ViewState["SelectedItem"] = value;
			}
		}

		/// <summary>
		/// Gets or sets the target URL for searches performed within the title
		/// </summary>
		[
		    Bindable(true),
		        Category("Behavior"),
		        Description("Gets or sets the URL for searches performed within the title."),
		        DefaultValue(""),
		]
		public virtual String SearchTargetURL 
		{
			get 
			{
				Object state = ViewState["SearchTargetURL"];
				if ( state != null ) 
				{
					return (String)state;
				}
				return "";
			}
			set 
			{
				ViewState["SearchTargetURL"] = value;
			}
		}

		#endregion

		#region Event Handlers

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad (e);
			//this.DataBind();
		}

		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender (e);

		    ArrayList itemsToSearch = (ArrayList) Context.Items["TitleBar:ItemsToSearch"];
			if (itemsToSearch != null && itemsToSearch.Count > 0 && _titleBarSearchDropDownList != null)
			{
				foreach (string[] item in itemsToSearch)
				{
					_titleBarSearchDropDownList.Items.Add(new ListItem(item[1], item[0]));
				}

				_titleBarSearchDropDownList.Items.Add(new ListItem(ResourceManager.GetString("TitleBar_SearchAll"), ":"));

				if (_titleBarSearchInArea != null)
					_titleBarSearchInArea.Visible = true;
			}
			else if (_titleBarSearchInArea != null)
					_titleBarSearchInArea.Visible = false;
		}

		protected void SearchButton_Click(Object sender, EventArgs e)
		{
			// redirect to the appropriate search results form
			if (Globals.IsNullorEmpty(_titleBarSearchText.Text))
				Page.Response.Redirect(SiteUrls.Instance().Search, true);
			else
			{
				SearchQuery query = new SearchQuery();

				query.QueryText = _titleBarSearchText.Text;
				if (_titleBarSearchDropDownList != null && !Globals.IsNullorEmpty(Page.Request.Form[_titleBarSearchDropDownList.UniqueID]))
				{
					string[] values = Page.Request.Form[_titleBarSearchDropDownList.UniqueID].Split(new char[] {':'}, 2);
					switch (values[0])
					{
						case "G":
							query.GroupsToSearch = new int[] { int.Parse(values[1]) };
							break;

						case "S":
							query.SectionsToSearch = new int[] { int.Parse(values[1]) };
							break;

                        case "U":
                            query.UsersToSearch = new int[] {int.Parse(values[1])};
                            break;

						case "T":
							query.Tags = values[1].Split(';');
							break;
					}
				}

				Page.Response.Redirect(Globals.GetSiteUrls().SearchForText(SearchProvider.Instance().SearchQueryString(query)), true );
			}
		}

		#endregion

		#region Methods

		public static void AddTagsToSearch(string[] tags, string name, HttpContext cntx)
		{
			ArrayList itemsToSearch = (ArrayList) cntx.Items["TitleBar:ItemsToSearch"];
			if (itemsToSearch == null)
			{
				itemsToSearch = new ArrayList();
				cntx.Items["TitleBar:ItemsToSearch"] = itemsToSearch;
			}

			itemsToSearch.Add(new string[] { "T:" + string.Join(";", tags), name });	
		}

		public static void AddGroupToSearch(int groupID, string name, HttpContext cntx)
		{
			ArrayList itemsToSearch = (ArrayList) cntx.Items["TitleBar:ItemsToSearch"];
			if (itemsToSearch == null)
			{
				itemsToSearch = new ArrayList();
				cntx.Items["TitleBar:ItemsToSearch"] = itemsToSearch;
			}

			itemsToSearch.Add(new string[] { "G:" + groupID.ToString(), name });	
		}

		public static void AddSectionToSearch(int sectionID, string name, HttpContext cntx)
		{
			ArrayList itemsToSearch = (ArrayList) cntx.Items["TitleBar:ItemsToSearch"];
			if (itemsToSearch == null)
			{
				itemsToSearch = new ArrayList();
				cntx.Items["TitleBar:ItemsToSearch"] = itemsToSearch;
			}

			itemsToSearch.Add(new string[] { "S:" + sectionID.ToString(), name });
		}

        public static void AddUsersToSearch(int userID, string name, HttpContext cntx)
        {
            ArrayList itemsToSearch = (ArrayList) cntx.Items["TitleBar:ItemsToSearch"];
            if (itemsToSearch == null)
            {
                itemsToSearch = new ArrayList();
                cntx.Items["TitleBar:ItemsToSearch"] = itemsToSearch;
            }

            itemsToSearch.Add(new string[] { "U:" + userID.ToString(), name });
        }

		#endregion

		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
		public void UpdateSiteTitle(string title)
		{
			if(_csContext.User.IsAdministrator)
			{
				SiteSettings settings = _csContext.SiteSettings;
				settings.SiteName = title;
				SiteSettingsManager.Save(settings);
			}
		}

		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
		public void UpdateSiteDescription(string desc)
		{
			if(_csContext.User.IsAdministrator)
			{
				SiteSettings settings = _csContext.SiteSettings;
				settings.SiteDescription  = desc;
				SiteSettingsManager.Save(settings);
			}
		}

		#region Skin Methods

		protected override void AttachChildControls()
		{
			_titleBarSearchText = (TextBox) FindControl("TitleBarSearchText");
			_titleBarSearchButton = FindButton("TitleBarSearchButton");
			_titleBarSiteName =  FindControl("TitleBarSiteName") as EditableLink;
			_titleBarDomainName = (HyperLink) FindControl("TitleBarDomainName");
			_titleBarSiteDescription =  FindControl("TitleBarSiteDescription") as InlineTextEdit;
			_titleBarSearchDropDownList = (DropDownList) FindControl("TitleBarSearchDropDownList");
			_titleBarSearchInArea = FindControl("TitleBarSearchInArea");

			SiteSettings settings = _csContext.SiteSettings;

			if(_csContext.User.IsAdministrator)
				AjaxManager.Register(this,"SiteSettings");

			#region Title/Description Initialization

			if (_titleBarSiteDescription != null) 
			{
				if (!settings.EnableSiteDescription) 
				{
					_titleBarSiteDescription.Visible = false;
				} 
				else 
				{
					_titleBarSiteDescription.Text = settings.SiteDescription;
					_titleBarSiteDescription.Visible = true;
					_titleBarSiteDescription.AjaxClientID = this.ClientID;
					_titleBarSiteDescription.AjaxFunction = string.Format("SiteSettings.UpdateSiteDescription('{0}',this.innerHTML,null);",this.ClientID);
				}
			}

			if (_titleBarSiteName != null) 
			{
			
				_titleBarSiteName.Text = settings.SiteName;
				_titleBarSiteName.ToolTip = settings.SiteDescription;
				_titleBarSiteName.NavigateUrl = Globals.GetSiteUrls().Home;
				_titleBarSiteName.Visible = true;
				_titleBarSiteName.AjaxClientID = this.ClientID;
				_titleBarSiteName.AjaxFunction = string.Format("SiteSettings.UpdateSiteTitle('{0}',this.innerHTML,null);",this.ClientID);

			}

			if (_titleBarDomainName != null) 
			{
				_titleBarDomainName.Text = settings.SiteDomain.ToLower();
				_titleBarDomainName.ToolTip = settings.SiteName;
				_titleBarDomainName.NavigateUrl = Globals.GetSiteUrls().ForumsHome;
				_titleBarDomainName.Visible = true;
			}

			#endregion

			#region Search Initialization

			if (_titleBarSearchButton != null)
			{
				_titleBarSearchButton.Click += new EventHandler(SearchButton_Click);
				_titleBarSearchButton.Text = ResourceManager.GetString("SearchRedirect_SearchButton");
				_titleBarSearchButton.CausesValidation = false;
			}
			
			#endregion

		}

		#endregion

	}


}
